#include "MathNodeItem.h"
#include "xNodeType_Math.h"
#include "xMappingNode.h"
#include "xInMappingPort.h"
#include "NodeInPort.h"

#include <QtGui/QPainter>

MathNodeItem::MathNodeItem(string name, xMappingTree* xmt, AbstractManager* manager )
	:NodeItem( name, xmt, manager )
{
	this->connect( this, SIGNAL( portListChanged( NodeItem * ) ), SLOT( onPortListChanged( NodeItem * ) ) );
}

MathNodeItem::MathNodeItem( xMappingNode* mappingNode , AbstractManager* manager )
	:NodeItem( mappingNode, manager )
{
	this->connect( this, SIGNAL( portListChanged( NodeItem * ) ), SLOT( onPortListChanged( NodeItem * ) ) );
}

void MathNodeItem::postPaint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) {
	// 如果是 node 是 math type，如果已經有設定了算式，則顯示一個小圖示來提示使用者
	xNodeType_Math* arithNode = dynamic_cast< xNodeType_Math * >( this->getMappingNode()->getNodeTypePtr() );
	assert( arithNode || !"dynamic_cast failed" );

	if (arithNode->haveFormula()){
		QImage image(":/resource/calculator-arrow-icon.png");
		painter->drawImage( 120, 5, image);
	}
}

bool MathNodeItem::validate() const {
	xNodeType_Math * type = dynamic_cast< xNodeType_Math * >( this->getMappingNode()->getNodeTypePtr() );
	assert( type || !"dynamic_cast failed" );

	if( !type->haveFormula() ) {
		return false;
	} else {
		return true;
	}
}

void MathNodeItem::onPortListChanged( NodeItem * ) {
	for( int i = 0; i < this->_mpnNode->getInportSize(); ++i ) {
	}
	int i = 0;
	for( auto it = this->_inportList.begin(); it != this->_inportList.end(); ++it ) {
		xInMappingPort * imp = this->_mpnNode->getInPort( i );
		std::ostringstream sout;
		sout << "var $" << i ;
		imp->setName( sout.str() );

		auto inp = *it;
		inp->setName( sout.str() );

		++i;
	}
}
